﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Register;
using BranchOfSansar.Sansar.Enquiry;
using BranchOfSansar.Register.Products;
using BranchOfSansar.Sansar.Transfer;
using System.Xml;

namespace BranchOfSansar.Register.Main
{
    public partial class frmContract_new : Form
    {
        private Sansar.Register.Contract cont;
        //private List<ContractAndEquipment> items = new List<ContractAndEquipment>();
        private List<Sansar.Register.vw_ContractEquipment> items = new List<Sansar.Register.vw_ContractEquipment>();
        private List<Sansar.Register.PaySchedule> Schedules = new List<Sansar.Register.PaySchedule>();
        //private 
        public frmContract_new()
        {
            InitializeComponent();            
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            frmCustomerList frm = new frmCustomerList(true);            
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                txtCustReg.Text = frm.selectedItem.CustRegister;
                txtCustReg.Tag = frm.selectedItem.CustNo;
                txtCustName.Text = frm.selectedItem.CustName;
                txtApartment.Text = frm.selectedItem.ApartCode;
                txtToot.Text = frm.selectedItem.DoorNo;
                loadApartment();
            }
        }

        private void loadData()
        {

            using (EnquiryClient ct = new EnquiryClient(Globals.Token))
            {                
                cmbCollector.Properties.Items.AddRange(ct.CollectorList().Select(s => new ComboItem() { Display = s.Name, StrValue = s.UserId.ToString() }).ToArray());
                cmbCollector.SelectedIndex = cmbCollector.Properties.Items.Count > 0 ? 0 : -1;
            }

            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new BranchOfSansar.Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                cmbBank.Enabled = true;
                cmbBank.Properties.Items.AddRange(tc.Banks());
                cmbBank.SelectedIndex = 0;
            }
        }
        private void loadEdit()
        {
         
                using (RegisterClient obj = new RegisterClient(Globals.Token))
                {
                    cont = obj.GetContract(Convert.ToInt32(this.Tag));
                    txtContractNo.Text = cont.ContractNo.ToString();

                    cmbCompany.SelectedIndex = 0;
                    txtUser.Text = cont.UserName;
                    if (cmbCategory.Visible == true)
                    {
                        cmbCategory.SelectedIndex = Convert.ToInt32(cont.PayType);
                    }
                    if (cmbBank.Visible == true)
                    {
                        Globals.setComboSelectedItem(cmbBank,Convert.ToInt32(cont.PayBank));
                    }
                    //cust,bair,toot,product,neesen ognoo,baitsaagch, shiljih buteegdehuun
                    
                    BranchOfSansar.Sansar.Register.vw_Customers cust1 = obj.GetCustomer(cont.CustNo);
                    txtCustReg.Tag = cont.CustNo;
                    txtCustReg.Text = cust1.CustRegister;
                    txtCustName.Text = cust1.CustName;
                    Sansar.Register.Apartment apart;
                    apart = obj.GetApartment(cont.ApartNo);
                    txtApartment.Text = apart.ApartCode;
                    txtApartment.Tag = cont.ApartNo;
                    txtApartName.Text = apart.Description;
                    txtToot.Text = cont.DoorNo;
                    txtUser.Text = cont.UserName;
                    txtPassword.Text = cont.Password;
                    //Sansar.Register.Product Prod = obj.GetProduct(cont.CurrProdCode);
                    txtProdOld.Text = cont.CurrProdCode.ToString();
                    //dtStart.DateTime = (DateTime)cont.StartDate;
                    Globals.setComboSelectedItem(cmbCollector,cont.Collector.ToString());
                    //Prod = obj.GetProduct(cont.NextProdCode);
                    //txtNextProd.Text = Prod.ProdCode.ToString();
                    //txtNextProdName.Text = Prod.Name;
                    txtDetail.Text = cont.Details;
                    txtC1.Text = cont.Balance.ToString("#,00");
                    //Globals.setComboSelectedItem(cmbQuarter, apt.QuarterCode);
                }
                // load prodname
                using (RegisterClient obj = new RegisterClient(Globals.Token))
                {
                    Sansar.Register.Product prod = obj.GetProduct(Convert.ToInt32(txtProdOld.Text));
                    if (prod == null)
                    {
                        Globals.Info(txtProdOld.Text + " кодтой бүтээгдэхүүн байхгүй байна!");
                        txtProdNameOld.Text = "";                        
                    }
                    else
                    {
                        txtProdNameOld.Text = prod.Name;
                    }
                }                
                //Schedule avah
                //using (RegisterClient obj = new RegisterClient(Globals.Token))
                //{
                 //   PaySchedule sched=obj.GetContractSchedule_contract(cont.ContractNo);
                  //  if(sched !=null)
                   // {
                   //     txtLeasing.Text = sched.PayBal.ToString();
                   //     cmbMonth.Text = sched.PayCount.ToString();
                   // }
                    //Globals.setComboSelectedItem(cmbCollector, obj.GetKass(apt.BankBranchNo).BankID.ToString());
                    //Globals.setComboSelectedItem(cmbKass, apt.BankBranchNo.ToString());
                //}                
            
        }
        private void loadCustomer()
        {
            using (RegisterClient obj = new RegisterClient(Globals.Token))
            {                
                Sansar.Register.vw_Customers cust = obj.GetCustomerByReg(txtCustReg.Text);
                if (cust == null)
                {
                    Globals.Info(txtCustReg.Text + " кодтой хэрэглэгч байхгүй байна!");
                    txtCustName.Text = "";
                    txtCustReg.Tag = "";
                    txtApartment.Text = "";
                    txtApartName.Text = "";
                    txtToot.Text = "";
                }
                else
                {
                    txtCustName.Text = cust.CustName;
                    txtCustReg.Tag = cust.CustNo.ToString();
                    txtApartment.Text = cust.ApartCode;
                    txtToot.Text = cust.DoorNo;
                    loadApartment();
                }
            }
        }
        private void loadApartment()
        {
            using (RegisterClient obj = new RegisterClient(Globals.Token))
            {
                Apartment ap = obj.GetApartmentByCode(txtApartment.Text);
                if (ap == null)
                {
                    Globals.Info(txtApartment.Text + " кодтой байр байхгүй байна!");
                    txtApartName.Text = "";
                    txtApartment.Tag = "";
                }
                else
                {
                    txtApartName.Text = ap.Description;
                    txtApartment.Tag = ap.Id.ToString();
                }
            }
        }
        private void loadProd()
        {
            if (string.IsNullOrWhiteSpace(txtProd.Text))
            {
                return;
            }
            using (RegisterClient obj = new RegisterClient(Globals.Token))
            {
                Sansar.Register.Product prod = obj.GetProduct(Convert.ToInt32(txtProd.Text));
                if (prod == null)
                {
                    Globals.Info(txtProd.Text + " кодтой бүтээгдэхүүн байхгүй байна!");
                    txtProdName.Text = "";
                    txtProd.Tag = 0;
                    txtProdPrice.Text = "0";
                    dtStart.DateTime = Globals.GetDate();
                }
                else
                {
                    txtProdName.Text = prod.Name;
                    txtProd.Tag = prod.Length;
                    txtProdPrice.Text = prod.Price.ToString();                    
                    items = obj.GetProductEquipments(prod.ProdCode).ToList();                    
                    BindGrid();
                }
                thinkSum();
            }
        }
        
        private void BindGrid()
        {
            gridEquip.DataSource = items;
            gridEquip.RefreshDataSource();
            thinkSum();
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            saveProd();
        }

        private void frmContract_Load(object sender, EventArgs e)
        {
            cmbCompany.SelectedIndex = 0;
            cmbCategory.SelectedIndex = 0;
            if (this.Tag == "new")
            {
                cmdSave.Visible = true;

            }
            else
            {
                //txtProd.Enabled=false;
                dtStart.Enabled=false;
                //gridEquip.Enabled=false;
                //txtLeasing.Enabled=false;
                //cmbMonth.Enabled = false;                
                //simpleButton5.Visible = false;
                //simpleButton3.Enabled = false;
            }
            //cmbMonth.SelectedIndex= 0;
            dtStart.DateTime = Globals.GetDate();
            loadData();
            loadEdit();
        }

        private void txtProd_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                loadProd();
            }
        }
        private void saveProd()
        {
            
            if (txtCustReg.Tag==null)
            {
                Globals.Warr("Харилцагчийн мэдээлэл дутуу байна!");
                return;
            }
            if (txtApartment.Tag==null)
            {
                Globals.Warr("Байрны мэдээлэл дутуу байна!");
                return;
            }
            if (txtProd.Tag==null && this.Tag=="new")
            {
                Globals.Warr("Бүтээгдэхүүний мэдээлэл дутуу байна!");
                return;
            }
            //if (txtPayd.Value < Convert.ToDecimal(txtAllPrice.Text) && this.Tag=="new")
            //{
            //    Globals.Warr("Төлсөн дүн дутуу байна!");
            //    return;
            //}
            
            if (!Globals.DoValidation(panelControl2))
            {
                return;
            }

            PaySchedule sched = new PaySchedule();
            cont.ContractNo = Convert.ToInt32(txtContractNo.Text);
            cont.ApartNo = Convert.ToInt32(txtApartment.Tag);
            cont.Collector = Convert.ToInt32(((ComboItem)cmbCollector.SelectedItem).StrValue);
            cont.ContDate = DateTime.Now;
            cont.CurrProdCode = Convert.ToInt32(txtProd.Text);
            cont.CustNo=Convert.ToInt32(txtCustReg.Tag);
            
            cont.Company = cmbCompany.SelectedIndex.ToString();
            cont.UserName = txtUser.Text;

            cont.PayType = cmbCategory.SelectedIndex;
            cont.PayBank = cmbBank.Visible ? ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbBank.SelectedItem).IntValue : 0;

            cont.Details=txtDetail.Text;
            cont.DoorNo=txtToot.Text;
            cont.EndDate = dtStart.DateTime.AddMonths(Convert.ToByte(txtProd.Tag));
            cont.StartDate = dtStart.DateTime;
            cont.Status = 1;
            //if (txtLeasing.Value > 0)
            //{
            //    sched.ContractNo = 1;
            //    sched.PayAmount = Convert.ToInt32(txtLeasing.Value / Convert.ToInt32(cmbMonth.Text));
            //    sched.PayBal = txtLeasing.Value;
            //    sched.PayCount = Convert.ToInt32(cmbMonth.Text);
            //    sched.PayDate = dtStart.DateTime.AddMonths(Convert.ToByte(txtProd.Tag));
            //    sched.IsContract = 1;
            //}
            //else
            //{
            //   sched.ContractNo = 0;
            //}

            //cont.NextProdCode = Convert.ToInt32(txtNextProd.Text);
            //cont.ProdCode = Convert.ToInt32(txtProd.Text);
            BranchOfSansar.Sansar.Register.Result r = new BranchOfSansar.Sansar.Register.Result();
            using (RegisterClient obj = new RegisterClient(Globals.Token))
            {
               
                r = obj.ChangeContract(cont, items.ToArray(), sched);
               
                if (r.Code != 0)
                {
                    Globals.Err(r.Message);
                    return;
                }
                
                txtContractNo.Text = r.RetData.ToString();
                cmdSave.Visible = false;
                //DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            DateTime dt = Globals.GetDate();
            using (TransferClient obj = new TransferClient(Globals.Token))
            {
                    obj.NewContractTransactions(Convert.ToInt64(txtContractNo.Text),
                        dt,
                        Convert.ToDecimal(txtEquipPrice.Text),
                        Convert.ToDecimal(txtProdPrice.Text),
                        txtPayd.Value,
                        Globals.UserId,
                        110,
                        "192.168.168.168", "Гэрээ шинэчлэв " + txtProdOld.Text + "->" + txtProd.Text, Convert.ToDecimal(txtC1.Text));
            }        
            Globals.Info(r.Message);            
        }
        //private void txtNextProd_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if (e.KeyChar == (char)Keys.Enter)
        //    {
        //        using (RegisterClient obj = new RegisterClient(Globals.Token))
        //        {
        //            Sansar.Register.Product prod = obj.GetProduct(Convert.ToInt32(txtNextProd.Text));
        //            if (prod == null)
        //            {
        //                Globals.Info(txtNextProd.Text + " кодтой бүтээгдэхүүн байхгүй байна!");
        //                txtNextProdName.Text = "";
        //            }
        //            else
        //            {
        //                txtNextProdName.Text = prod.Name;                                                
        //            }
        //        }
        //    }
        //}

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (viewItems.SelectedRowsCount < 1)
            {
                Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
                return;
            }
            Sansar.Register.vw_ContractEquipment rem = (Sansar.Register.vw_ContractEquipment)viewItems.GetRow(viewItems.GetSelectedRows()[0]);
            items.Remove(rem);            
            BindGrid();
            //gridEquip.
        }

        private void btnAddService_Click(object sender, EventArgs e)
        {
            frmAddSchedule frm = new frmAddSchedule();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                Schedules.Add(frm.addItem);
                BindGrid();                
            }
        }

        //private void btnDelService_Click(object sender, EventArgs e)
        //{
        //    if (viewSched.SelectedRowsCount < 1)
        //    {
        //        Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
        //        return;
        //    }
        //    Sansar.Register.PaySchedule s = (Sansar.Register.PaySchedule)viewSched.GetRow(viewSched.GetSelectedRows()[0]);
        //    Schedules.Remove(s);
        //    BindGrid();
        //}

        private void txtCustReg_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                loadCustomer();
            }
        }

        private void txtApartment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                loadApartment();
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            frmApartmentList frm = new frmApartmentList();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                txtApartment.Text = frm.SelectedItem.ApartCode.ToString();
                txtApartment.Tag = frm.SelectedItem.Id;
                txtApartName.Text = frm.SelectedItem.Description;
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            frmProduct frm = new frmProduct();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                txtProd.Text = frm.SelectedItem.ProdCode.ToString();                
                //txtProdName.Text = frm.SelectedItem.Name;
                //txtProdPrice.Text = frm.SelectedItem.Price.ToString();
                loadProd();
                thinkSum();
            }
        }
        private void thinkSum()
        {
            try
            {
                dtEnd.DateTime = dtStart.DateTime.AddMonths(Convert.ToInt32(String.IsNullOrEmpty(txtProd.Tag.ToString()) ? "0" : txtProd.Tag.ToString()));
                txtEquipPrice.Text = (Convert.ToDouble(String.IsNullOrEmpty(gridColumn2.SummaryText) ? "0" : gridColumn2.SummaryText)).ToString();
                txtAllPrice.Text = (Convert.ToDouble(txtProdPrice.Text) + Convert.ToDouble(txtEquipPrice.Text) + Convert.ToDouble(txtC1.Text)).ToString();
                txtPayd.Text = txtAllPrice.Text;
                txtC2.Text = (Convert.ToDouble(txtAllPrice.Text) - Convert.ToDouble(txtPayd.Text)).ToString("#,##0");

            }
            catch(Exception ex)
            {

            }
        }
        //private void simpleButton4_Click(object sender, EventArgs e)
        //{
        //    frmProduct frm = new frmProduct();
        //    if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
        //    {
        //        txtNextProd.Text = frm.SelectedItem.ProdCode.ToString();
        //        txtNextProdName.Text = frm.SelectedItem.Name;
        //    }
        //}

        private void cmdExit_Click(object sender, EventArgs e)
        {
            if (cmdSave.Visible == false)
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;                
            }
            else
            {
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
            }
        }

        private void txtProd_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtPayd_EditValueChanged(object sender, EventArgs e)
        {
            
            // 
        }

        private void cmbKass_EditValueChanged(object sender, EventArgs e)
        {

        }

        

        private void txtLeasing_EditValueChanged(object sender, EventArgs e)
        {
            thinkSum();
        }

        private void dtStart_EditValueChanged(object sender, EventArgs e)
        {
            thinkSum();
        }

        private void txtApartment_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtCustReg_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void cmbCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCompany.SelectedIndex == 0)
            {
                //lblUser.Visible = false;
                //txtUser.Visible = false;
                //txtUser.BackColor = Color.Black;
            }
            else
            {
                //lblUser.Visible = true;
                //txtUser.Visible = true;
                //txtUser.BackColor = txtCustReg.BackColor;
            }
        }

        private void cmbTransCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCategory.SelectedIndex == 0)
            {
                lblBank.Visible = true;
                cmbBank.Visible = true;                
            }
            else
            {
                lblBank.Visible = false;
                cmbBank.Visible = false;
            }
        }

        private void viewItems_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            viewItems.UpdateTotalSummary();
            thinkSum();            
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            
        }

        private void viewItems_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            
        }

        private void viewItems_ColumnUnbountExpressionChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e)
        {            
        }

        private void gridEquip_Click(object sender, EventArgs e)
        {

        }

        private void txtPayd_EditValueChanged_1(object sender, EventArgs e)
        {
            txtC2.Text = (Convert.ToDouble(txtAllPrice.Text) - Convert.ToDouble(txtPayd.Text)).ToString("#,##0");
        }
        
    }
}
